package com.g001.model.GUI;

import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.geom.Vector2f;
import org.newdawn.slick.state.StateBasedGame;

import com.g001.model.Entity;
import com.g001.util.CachedResourceLoader;

public class Clock extends Entity {

	public static Long DURATION_TURN = 16000l;
	private Long duration; // time to display
	private long countDown; // in ms
	private long endTime;
	private boolean stop;
	private final static float WIDTH = CachedResourceLoader.font.getWidth("00:00");
	
	private boolean playerAsPlayed;
	
	public Clock() throws SlickException {
		super("Battle Clock", "data/g001/blocks.png", new Vector2f(0,0));
		init(DURATION_TURN);
	}
	
	
	private void init(final Long duration) {
		this.duration = duration;
		image = image.getSubImage(0, 378, 80, 65);	
		reset();
	}

	public void reset(){
		playerAsPlayed = false;
		stop = false;
		this.endTime = System.currentTimeMillis() + duration;
		this.countDown = duration/1000;
	}
	
	
	@Override
	public void render(GameContainer container, StateBasedGame game, Graphics g)
			throws SlickException {
		g.drawImage(image, container.getWidth()/2-image.getWidth()/2, 0);
		CachedResourceLoader.font.drawString((container.getWidth()-WIDTH)/2-7 ,30, String.valueOf((countDown>9?"00:"+countDown:"00:0"+countDown)));
	}

	@Override
	public void update(GameContainer container, StateBasedGame game, int delta)
			throws SlickException {
		if(!stop) {
			countDown = (endTime-System.currentTimeMillis()) / 1000;
			if(countDown<0) {
				countDown = 0;
			}
		}
	}
	
	public boolean timeOver() {
		return countDown <= 0;
	}

	public void stop() {
		stop = true;
	}

	public boolean isPlayerAsPlayed() {
		return playerAsPlayed;
	}

	public void setPlayerAsPlayed(boolean playerAsPlayed) {
		this.playerAsPlayed = playerAsPlayed;
	}

	public void start() {
		stop = false;
	}
	
	// completly fake - just give the impression it thinks
	public boolean isComputerIsReadyToPlay(){
		return countDown<=DURATION_TURN/1000-3;
	}

}
